import { atom } from 'jotai'
import { Settings, Theme, DataStorePlatform } from '@/types'
import { atomWithStorage } from 'jotai/utils'
import { focusAtom } from 'jotai-optics'

const defaultSettings: Settings = {
  showWordCount: true,
  showTokenCount: false,
  showTokenUsed: true,
  showModelName: true,
  showMessageTimestamp: false,

  autoGenerateTitle: true,

  theme: Theme.FollowSystem,
  language: 'en',
}

type DataStoreConfig = Record<DataStorePlatform, { url: string, key: string }>

export const settingsAtom = atomWithStorage<Settings>('settings', defaultSettings)
export const showWordCountAtom = focusAtom(settingsAtom, optic => optic.prop('showWordCount'))
export const showTokenCountAtom = focusAtom(settingsAtom, optic => optic.prop('showTokenCount'))
export const showModelNameAtom = focusAtom(settingsAtom, optic => optic.prop('showModelName'))
export const showMessageTimestampAtom = focusAtom(settingsAtom, optic => optic.prop('showMessageTimestamp'))

export const themeAtom = focusAtom(settingsAtom, optic => optic.prop('theme'))
export const activeThemeAtom = atom<'light' | 'dark'>('light')
export const languageAtom = focusAtom(settingsAtom, optic => optic.prop('language'))

export const autoGenerateTitleAtom = focusAtom(settingsAtom, optic => optic.prop('autoGenerateTitle'))

export const syncConfigAtom = atomWithStorage<DataStoreConfig>('syncConfig', Object.values(DataStorePlatform).reduce((t, platform) => {
  t[platform] = {
    url: '',
    key: '',
  }
  return t
}, {} as DataStoreConfig))

export const activeSyncTypeAtom = atom<DataStorePlatform>(DataStorePlatform.Gist)
